import {
  Shader,
  ShaderData,
  ShaderProperty,
  ShaderPool,
  ShaderProgram,
  ShaderProgramPool,
  ShaderMacro,
  ShaderMacroCollection,
  ShaderDataGroup,
  ShaderLib
} from "@nirvana/shaders";
import { Color } from "@nirvana/math";
import { WebGLCanvas } from "@nirvana/canvas";

console.log(ShaderLib);

ShaderPool.init();

const shaderMap: Record<string, Shader> = Shader._shaderMap;
console.log(shaderMap);

const someShader: Shader = Shader.find("blinn-phong");
console.log(someShader);

//-- Shader 代码
const vertexSource = `
  uniform mat4 u_MVPMat;

  attribute vec3 POSITION; 
  attribute vec2 TEXCOORD_0;
  varying vec2 v_uv;

  void main() {
    gl_Position = u_MVPMat * vec4(POSITION, 1.0);
    v_uv = TEXCOORD_0;
  }
  `;

const fragmentSource = `
  uniform vec4 u_color;
  varying vec2 v_uv;

  #ifdef TEXTURE
    uniform sampler2D u_texture;
  #endif

  void main() {
    vec4 color = u_color;

    #ifdef TEXTURE
      color *= texture2D(u_texture, v_uv);
    #endif

    gl_FragColor = color;

  }
  `;

// 创建 shader（整个 runtime 只需要创建一次）
const demo = Shader.create("demo", vertexSource, fragmentSource);
console.log(demo, Shader.find("demo"));

const shaderMacrolMap: Record<string, ShaderMacro> = Shader._macroMap;
console.log(shaderMacrolMap);

const shaderMacroCollection: ShaderMacroCollection = new ShaderMacroCollection();
console.log(shaderMacroCollection);

// meta(viewport)、devicePixelRatio、canvas.width

// 使用使用 Canvas
let canvas = document.getElementById("engine-nirvana");
// console.log(canvas);

const webCanvas = new WebGLCanvas(canvas, {
  // fullScreen: true, // 自动放大全屏
  // fixWidth: 500, // 放大
  // auto: true // 页面设置了canvas 样式
  // 2d: true,
});
// webCanvas.fullScreen();
const engine = webCanvas.engine;
const gl = engine.gl;
const pool1: ShaderProgramPool = new ShaderProgramPool();
const program: ShaderProgram = demo.getShaderProgram(engine.gl, shaderMacroCollection, pool1);
console.log(program);

const someMacro1: Shader = Shader.getMacroByName("O3_HAS_VERTEXCOLOR");
const someMacro2: Shader = Shader.getMacroByName("O3_HAS_VERTEXALPHA");
console.log(someMacro1, someMacro2);

const propertyMap: Record<string, ShaderProperty> = Shader._propertyNameMap;
console.log(propertyMap);

const _viewMatrixProperty: Shader = Shader.getPropertyByName("u_MVPMat");
console.log(_viewMatrixProperty);

const shaderData: ShaderData = new ShaderData(ShaderDataGroup.Material);
console.log(ShaderDataGroup, shaderData);
shaderData.setColor("u_color", new Color(1, 0, 0, 1)); // { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }

engine.update = (gl) => {
  // console.log('--');
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // 用上面指定的颜色清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);
  // 点start 一

  // 点end
};
